package cn.veliger.springai.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author veliger
 * create on 2025-05-28
 **/
@Configuration
public class AiConfig {

    /**
     * openai chat model
     *
     * @param model
     * @return
     */
    @Bean
    public ChatClient chatClient(OpenAiChatModel model) {
        return ChatClient.builder(model)
                .build();
    }

    /**
     * 有会话记忆chatClient
     *
     * @param chatClientBuilder
     * @return
     */
    @Bean
    public ChatClient memoryChatClient(ChatClient.Builder chatClientBuilder, ChatMemoryRepository chatMemoryRepository) {
        // 基于内存的会话记忆
        //ChatMemoryRepository chatMemoryRepository = new InMemoryChatMemoryRepository();
        // 会话记录
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(10)
                .build();
        return chatClientBuilder
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .build();
    }
}
